# %%
from conn import (
    ac_task_col,
    clip_annotated_record,
    static_auto_label,
    check_frame_label_col,
)


# %%

update_time = "2025-04-07 14:00:00"

# 获取 clip_ids 的方式可能不同
filter = {
    "task_type": "vis_proc_19",
    "run_id": "20250331_psd",
    "status": "success",
    "updated_at": {"$lte": update_time},
}

# 拍下序，保持输出的稳定
run_success_clip_ids = static_auto_label.distinct("clip_id", filter=filter)
run_success_clip_ids.sort()
print("success clip id cnt", len(run_success_clip_ids))

# %%

with open("clip_ids_19.txt", "w") as f:
    f.write("\n".join(run_success_clip_ids))

# %%

# 这个文件是 sumengxun 提供的，需要求两者交集来对 clip_ids 进行重置
invalid_clip_ids = []
with open("clip_id_invalid_19.txt", "r") as f:
    for line in f:
        invalid_clip_ids.append(line.strip())
print("invalid clip id cnt", len(invalid_clip_ids))

clip_ids = list(set(run_success_clip_ids) & set(invalid_clip_ids))
print("intersection clip id cnt", len(clip_ids))
for clip_id in clip_ids:
    print(clip_id)

# %%
clip_ids = []
with open("./clip_ids_target_100_19.txt", "r") as fp:
    for line in fp:
        clip_ids.append(line.strip())
print(clip_ids)


# %%
# 对前 100 个进行操作
target_clip_ids = clip_ids[:100]
annotate_type = 19

# %%


def handle_one_clip(clip_id):
    print("\n" + clip_id)

    # 3. ac task 记录更新成 2 进行中，并设置优先级
    cur_task = ac_task_col.find_one(
        dict(clip_ids=clip_id, annotate_type=annotate_type),
        {"task_name": 1, "status": 1, "priority": 1},
    )

    assert cur_task is not None

    print(cur_task["task_name"], cur_task["priority"])

    update_info = dict(priority=4)
    # if cur_task["status"] == 3:
    #     update_info["status"] = 2
    ac_task_col.update_one(
        {"_id": cur_task["_id"]},
        {"$set": update_info},
    )

    print("task status", cur_task["status"])
    # 1. 删除之前的标注记录？
    # cnt = check_frame_label_col.count_documents(
    #     dict(clip_id=clip_id, annotate_type=annotate_type)
    # )
    # print("origin check frame cnt ", cnt)
    # if cnt != 0:
    #     check_frame_label_col.delete_many(
    #         dict(clip_id=clip_id, annotate_type=annotate_type)
    #     )

    # 2. clip accept_status 变成 10 进行中
    # cur_clip = clip_annotated_record.find_one(
    #     dict(clip_id=clip_id, annotate_type=annotate_type), {"accept_status": 1}
    # )
    # print("clip status", cur_clip.get("accept_status", -1))
    # if cur_clip.get("accept_status", -1) != 10:
    #     clip_annotated_record.update_one(
    #         {"_id": cur_clip["_id"]},
    #         {"$set": {"accept_status": 10}},
    #     )

    return True


for clip_id in target_clip_ids:
    handle_one_clip(clip_id)

# %%

with open("clip_ids_target_100_19.txt", "w") as fp:
    fp.write("\n".join(target_clip_ids))
